var selectCurPage = 1;
var selectPageSize = 20;
var selectPara = {
    value: decodeURI(window.getUrlParam('keyword') || ''),
    platId: 4,
    order_by: 'fans_count',
    order_id: 1
};
var tagMap = {};
var selectPage = {
    getList: function() {
        selectPara.pageSize = selectPageSize;
        $.ajax({
            url: window.domain + window.requestUrl.selectSearchUrl,
            type: 'get',
            data: selectPara,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    var pager = res.data.result;
                    tagMap = res.data.tags;
                    selectPage.initPaging(pager.pages, pager.total, res);
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
    },
    initPaging: function(totalPage, totalDataNum, res) {
        var self = this,
            ele = $('[data-role="dirPaging"]');
            if(totalDataNum > 0) {
                ele.show();
                var pagination = ele.pagination(totalDataNum, {
                    num_edge_entries: 1,
                    num_display_entries: 4,
                    callback: function(page_index) {
                        if(page_index == 0) {

                            var pageData = res.data.result.list;
                            selectPage.randerList(pageData);
                        } else {
                            selectCurPage = page_index + 1;
                            selectPage.getPageDates();
                        }
                    },
                    items_per_page: selectPageSize,
                    prev_text: "&lt;&lt;上一页",
                    next_text: "下一页&gt;&gt;",
                    link_to: "javascript:;"
                });

            }else {
                ele.hide();
                $('[data-role="result"]').html('<tr><td  colspan="7" style="text-align: center;line-height: 100px;font-size: 18px;">搜索结果暂无该媒体数据</td></tr>')
            }
    },
    getPageDates: function() {
        var self = this;
        selectPara.pageNum = selectCurPage;
        selectPara.pageSize = selectPageSize;
        $.ajax({
            url: window.domain + window.requestUrl.selectSearchUrl,
            type: 'get',
            data: selectPara,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }

                // 同步页码
                var totalPage = res.data.result.pages;

                var pageData = res.data.result.list;
                var result = res.data.result;
                self.randerList(pageData);
            },
            error: function() {
                // console.log('分页接口失败');
            }
        });
    },
    randerList: function(pageData) {
        var tpl = '';
        $.each(pageData, function(index, item) {
            var titleTpl = '';
            item.tags = JSON.parse(item.tags)
            if(item.tags.length > 0) {
                var tagTpl = '';
                $.each(item.tags, function(indexDir, itemDir) {
                    if(indexDir > 2) return;
                    tagTpl += tagMap[itemDir]+' ';
                })
                titleTpl = '<p>'+item.title+'</p><p class="item-desc">'+tagTpl+'</p>';
            } else {
                titleTpl = '<p style="line-height:50px;">'+item.title+'</p>';
            }
            var dangqi = '';
            if(item.hasFreeSchedInWeek) {
                dangqi = '有';
            } else {
                dangqi = '无';
            }

            var openqq = '';
            if(window.isLogin) {
                openqq = '<a href="tencent://message/?uin='+item.qq+'&Site=yoomeda.com&Menu=yes" target="_blank">\
                            <img src="http://wpa.qq.com/pa?p=2:'+item.qq+':41" alt="点击这里给我发消息" title="点击这里给我发消息">\
                        </a>';
            } else {
                openqq = '<a href="javascript:;" data-role="tologin">\
                            <img src="http://wpa.qq.com/pa?p=2:'+item.qq+':41" alt="点击这里给我发消息" title="点击这里给我发消息">\
                        </a>';
            }
            var avgReadCountReal = item.avgReadCount ? item.avgReadCount : '无';
            tpl += '<tr>\
                        <td>\
                            <div class="tr-main">\
                                <a href="./weixin-detail.html?id='+item.id+'" target="_blank">\
                                    <img src="'+item.iconUrl+'" alt="'+item.title+'">\
                                </a>\
                                <div class="tr-main__name">\
                                    <a href="./weixin-detail.html?id='+item.id+'" target="_blank">'+titleTpl+'</a>\
                                </div>\
                            </div>\
                        </td>\
                        <td>'+item.fansCount+'</td>\
                        <td>'+avgReadCountReal+'</td>\
                        <td>'+((item.price1 == -1) ? '无' : item.price1)+'</td>\
                        <td>'+((item.price2 == -1) ? '无' : item.price2)+'</td>\
                        <td>'+dangqi+'</td>\
                        <td>'+openqq+'</td>\
                    </tr>';
        })
        $('[data-role="result"]').html(tpl);
    }
}

var select = {
    more: function() {
        $(document).on('click', '[data-role="more"]', function() {
            var $this = $(this);
            if($this.attr('data-show') == 1) {
                $this.closest('.select-tab__item').css({
                    height: '34px'
                });
                $this.attr('data-show', 0).html('更多');

            } else {
                $this.closest('.select-tab__item').css({
                    height: $this.prev('.list-tag').height() - 21 + 'px'
                });
                $this.attr('data-show', 1).html('收起');
            }

        })
    },
    getItem: function() {
        $.ajax({
            url: window.domain + window.requestUrl.filtrateTagsUrl,
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {
                platId: 4
            },
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                var result = res.data.result;
                var tpl = '';
                $.each(result, function(index, item) {
                    tpl += '<li class="select-tab__item" data-type="'+item.type+'">\
                                <div class="left_zhlx">'+item.type_name+'</div>\
                                <ul class="list-tag">\
                                    <li class="item-tag is-active" data-id="-1">\
                                        <span>不限</span>\
                                    </li>';
                    $.each(item.tags, function(indexDir, itemDir) {
                        tpl += '<li class="item-tag" data-id="'+itemDir.id+'">\
                                    <span>'+itemDir.tag+'</span>\
                                </li>';
                    })
                    if(item.tags.length > 10) {
                        tpl += '</ul><div class="more" data-role="more">更多</div>';
                    } else {
                        tpl += '</ul>';
                    }
                })
                $('[data-role="selectTags"]').html(tpl);

            },
            error: function() {
            }
        });
    },
    selectItem: function() {
        $(document).on('click', '.item-tag', function() {
            selectPara = {
                value: decodeURI(window.getUrlParam('keyword') || ''),
                platId: 4
            };
            var $this = $(this);
            $this.closest('.select-tab__item').find('.is-active').removeClass('is-active');
            $this.addClass('is-active');
            selectPara.tagIds = '';
            $.each($('.item-tag.is-active'), function(index, item) {
                var $$this = $(this);
                if($$this.attr('data-id') != -1) {
                    selectPara.tagIds += $$this.attr('data-id') + ',';
                }
            })
            selectPara.tagIds = decodeURIComponent(selectPara.tagIds.substring(0, selectPara.tagIds.length - 1));
            selectPage.getList();
        })
    },
    loginStatus: function() {
        $.ajax({
            url: window.domain + window.requestUrl.userUrl,
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                selectPage.getList();
                if(res.status) {
                    window.isLogin = true;
                } else {
                    window.isLogin = false;
                }
            },
            error: function(e) {
            }
        })
    },
    tologin: function() {
        $(document).on('click', '[data-role="tologin"]', function() {
            iosOverlay({
                text: '请先登录！',
                duration: 1500
            });
        })
    },
    init: function() {
        this.selectItem();
        this.more();
        this.loginStatus();
        this.tologin();
        this.getItem();
    }
}

select.init();
